import Taro from '@tarojs/taro'
import { View, Text, Button } from '@tarojs/components'
import { useDebtForm } from '../../hooks/useDebtForm'
import { DebtForm } from '../../components/DebtForm'
import { PaymentDetails } from '../../components/PaymentDetails'
import { calculatePaymentPlan } from '../../utils/calculation'
import { debtService } from '../../utils/cloud'

export default function Debt() {
  const initialFormData = {
    creditor: '', // 债权人
    loanAmount: '', // 借款金额
    loanPeriod: '', // 借款周期（月）
    rate: '', // 年利率
    paymentType: 'equalPayment', // 还款方式
    loanDate: '', // 借款日期
    paymentDate: '', // 首次还款日期
    paidPeriods: '0', // 已还期数
    remainingPeriods: '', // 剩余期数
    totalInterest: '', // 总利息
    totalPayment: '', // 共计还款
    remark: '', // 备注
    totalPeriods: '' // 添加总期数
  }

  const {
    formData,
    setFormData,
    creditorOptions,
    calculation,
    setCalculation,
    showDetails,
    setShowDetails,
    handleCreditorChange,
    handleInputChange,
    handleSubmit
  } = useDebtForm(initialFormData)

  // 还款方式选项
  const paymentTypeOptions = [
    { label: '等额本息', value: 'equalPayment' },
    { label: '等额本金', value: 'equalPrincipal' },
    { label: '先息后本', value: 'interestFirst' },
    { label: '免息', value: 'noInterest' }
  ]

  const fields = [
    {
      name: 'loanAmount',
      title: '借款金额',
      type: 'digit',
      placeholder: '请输入借款金额',
      required: true
    },
    {
      name: 'loanPeriod',
      title: '借款周期',
      type: 'number',
      placeholder: '请输入借款周期(月)',
      required: true
    },
    {
      name: 'rate',
      title: '年利率',
      type: 'digit',
      placeholder: '请输入年利率(%)',
      required: true
    },
    {
      name: 'loanDate',
      title: '借款日期',
      type: 'date',
      placeholder: '请选择借款日期',
      required: true
    },
    {
      name: 'paymentDate',
      title: '首次还款日期',
      type: 'date',
      placeholder: '请选择首次还款日期',
      required: true
    },
    { name: 'remark', title: '备注', type: 'text', placeholder: '请输入备注' }
  ]

  const columns = [
    { key: 'period', title: '期数' },
    { key: 'payment', title: '月供' },
    { key: 'principal', title: '本金' },
    { key: 'interest', title: '利息' },
    { key: 'remainingPrincipal', title: '剩余本金', width: '2' },
    { key: 'paymentDate', title: '还款日', width: '2' },
    {
      key: 'isPaid',
      title: '状态',
      color: 'isPaid',
      width: '2',
      render: value => (value ? '已还款' : '未还款')
    }
  ]

  // 验证必填项
  const validateRequiredFields = () => {
    const requiredFields = [
      { field: 'creditor', name: '债权人' },
      { field: 'loanAmount', name: '借款金额' },
      { field: 'loanPeriod', name: '借款周期' },
      { field: 'rate', name: '年利率' },
      { field: 'paymentType', name: '还款方式' },
      { field: 'loanDate', name: '借款日期' },
      { field: 'paymentDate', name: '还款日' }
    ]

    for (const { field, name } of requiredFields) {
      if (!formData[field]) {
        Taro.showToast({
          title: `请填写${name}`,
          icon: 'none'
        })
        return false
      }
    }

    return true
  }

  // 处理还款方式变化
  const handlePaymentTypeChange = value => {
    const selectedPaymentType = paymentTypeOptions[value.detail.value]
    setFormData({
      ...formData,
      paymentType: selectedPaymentType.value
    })
  }

  // 计算还款计划
  const calculate = () => {
    if (!validateRequiredFields()) {
      return
    }

    const { loanAmount, rate, loanPeriod, paymentDate, paymentType, loanDate } = formData

    // 计算还款计划
    const result = calculatePaymentPlan(
      parseFloat(loanAmount),
      parseFloat(rate),
      parseInt(loanPeriod),
      loanDate,
      paymentDate,
      paymentType
    )

    // 转换数据结构以匹配 PaymentDetails 组件
    const formattedResult = {
      remainingTotal: result.totalPayment,
      remainingPrincipal: loanAmount,
      remainingInterest: result.totalInterest,
      monthlyPayment: result.monthlyPayment,
      paymentPlan: result.monthlyDetails.map(detail => ({
        period: detail.type === 'principal' ? '本金期' : `${detail.month}期`,
        payment: detail.payment.toFixed(2),
        principal: detail.principal.toFixed(2),
        interest: detail.interest.toFixed(2),
        remainingPrincipal: detail.remaining.toFixed(2),
        paymentDate: detail.paymentDate,
        // 不再保存 isPaid 状态，而是在使用时实时计算
        type: detail.type
      }))
    }

    // 更新表单数据
    setFormData({
      ...formData,
      paidPeriods: result.paidPeriods.toString(),
      remainingPeriods: result.remainingPeriods.toString(),
      totalInterest: result.totalInterest.toFixed(2),
      totalPayment: result.totalPayment.toFixed(2),
      totalPeriods: result.totalPeriods.toString()
    })

    setCalculation(formattedResult)
  }

  // 保存数据
  const handleSave = async () => {
    if (!validateRequiredFields()) {
      return
    }

    if (!calculation) {
      Taro.showToast({
        title: '请先计算还款计划',
        icon: 'none'
      })
      return
    }

    try {
      // 添加新数据
      const newDebt = {
        creditor: formData.creditor,
        loanAmount: formData.loanAmount,
        loanPeriod: formData.loanPeriod,
        rate: formData.rate,
        paymentType: formData.paymentType,
        loanDate: formData.loanDate,
        paymentDate: formData.paymentDate,
        paidPeriods: formData.paidPeriods,
        remainingPeriods: formData.remainingPeriods,
        totalInterest: formData.totalInterest,
        totalPayment: formData.totalPayment,
        remark: formData.remark,
        calculation: calculation
      }

      const result = await debtService.addDebt(newDebt)

      if (result.success) {
        Taro.showToast({
          title: '保存成功',
          icon: 'success'
        })

        // 返回上一页
        Taro.navigateTo({ url: '/pages/index/index' })
      } else {
        throw new Error(result.error)
      }
    } catch (error) {
      Taro.showToast({
        title: '保存失败',
        icon: 'error'
      })
    }
  }

  return (
    <View className="min-h-screen bg-gray-100 p-4">
      <DebtForm
        formData={formData}
        creditorOptions={creditorOptions}
        paymentTypeOptions={paymentTypeOptions}
        handleCreditorChange={handleCreditorChange}
        handlePaymentTypeChange={handlePaymentTypeChange}
        handleInputChange={handleInputChange}
        fields={fields}
      >
        {calculation && (
          <PaymentDetails
            details={calculation}
            columns={columns}
            showDetails={showDetails}
            setShowDetails={setShowDetails}
          />
        )}
      </DebtForm>

      <View className="gap-2 mt-4 flex justify-center">
        <Button
          type="primary"
          onClick={calculate}
          className="flex-1 bg-blue-500 hover:bg-blue-600 text-white shadow-md"
        >
          计算还款计划
        </Button>
        {calculation && (
          <Button
            type="primary"
            onClick={handleSave}
            className={`${
              calculation ? 'bg-blue-500 hover:bg-blue-600' : 'bg-gray-400'
            } flex-1 text-white shadow-md`}
          >
            保存
          </Button>
        )}
      </View>
    </View>
  )
}
